<!--云闪推——开头/片尾库——上传视频-->
<template>
  <!--  需做限制，如果已有4个视频，那么只能再上传1个视频 -->
  <ele-modal width="460px"
             :visible="visible"
             :append-to-body="true"
             :close-on-click-modal="true"
             custom-class="ele-dialog-form"
             :title="titles"
             limit="30"
             @update:visible="updateVisible">
    <!--判断视频最大上传个数为5-->
    <!--
	-->
    <!--      -->
    <!--测试是否限制了3秒视频-->
    <el-upload ref="upload"
               :disabled="loading == true?true:false"
               :file-list="fileList"
               :on-change="onUpload"
               :auto-upload="false"
               :before-upload="beforeAvatarUpload"
               :on-exceed="handleExceed"
               :limit="1"
               accept=".mp4,.3gp,.mov"
               class="upload-demo"
               drag
               :action="ossUrl"
               multiple>
      <i class="el-icon-upload"
         v-show="loading == false"></i>
      <el-image v-show="loading == true"
                style="width: 67px;    margin: 40px 0 16px;
		line-height: 50px;"
                :src="require('/src/assets/loading.gif')"></el-image>
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      <div class="el-upload__tip"
           slot="tip">只能上传.mp4,.3gp,.mov文件，且不超过30M(视频时长最低3s)</div>
    </el-upload>
    <template v-slot:footer>
      <el-button size="small"
                 @click="updateVisible(false)">
        取消上传
      </el-button>
      <el-button :loading="loading"
                 size="small"
                 type="primary"
                 @click.stop="selectVideo()">
        开始上传
      </el-button>
    </template>
  </ele-modal>
</template>
	
	<script>
import { registerAssetsMedia, registerMedia, userOssSignature, mainOssSignature } from "@/api/creatCenter/material";
import { getToken } from "@/utils/token-util";
import { addTrailer } from "@/api/lncomingManagement/openOrEndLibrary"

import axios from "axios";

export default {
  name: "file-upload",
  props: {
    // 弹窗是否打开
    visible: Boolean,
  },
  data () {
    return {
      isMp4success: 0,
      ossUrl: localStorage.getItem('ossUrl') ? localStorage.getItem('ossUrl') : '', //上传图片action
      loading: false,
      fileList: [],
      data: {},
      isFile: false,
      // 用于判断，是否上传到最后一个
      isNum: 0,
      residueLength: 0, // 上传视频剩余个数
      titles: '', //弹框名称
      types: '', // 1:片头 2：片尾 标识
    };
  },
  created () {
  },
  methods: {
    // type 1:片头 2：片尾
    show (haveLength, type) {
      this.types = type
      this.titles = type == 1 ? '上传片头视频' : '上传片尾视频'
      // haveLength:已有的视频个数，视频最多5个
      this.residueLength = 5 - Number(haveLength)
      console.log('this.residueLength', this.residueLength)
    },
    async selectVideo () {
      this.isNum = 0
      console.log("this.fileList.length", this.fileList.length, 'isMp4success', this.isMp4success)
      if (this.fileList.length < 1) {
        console.log("请选择文件后提交")
        this.$message.error('请选择文件后提交');
        return
      }
      let isLt = true
      for (let i = 0; i < this.fileList.length; i++) {
        // 判断是否小于2mb
        if (this.fileList[i].size / 1024 / 1024 > 30) {
          isLt = false
        }
      }
      if (!isLt) {
        for (let i = 0; i < this.fileList.length; i++) {
          // 判断是否小于2mb
          if (this.fileList[i].size / 1024 / 1024 > 30) {
            this.fileList.splice(i, 1)
          }
        }
        this.$message.error("请上传小于30MB文件");
        return
      }
      this.$refs.upload.submit();  // 图片上传进度(修改隐藏)


      this.isFile = true
      console.log('this.fileList.length222222', this.fileList.length, 'isMp4success', this.isMp4success)
      this.data = await mainOssSignature()
      if (this.isMp4success <= 3) {
        this.$message.error('上传视频长度不能低于3秒');
        console.log('停止上传this.fileList', this.fileList)
        return
      }
      console.log('this.fileList.length32423', this.fileList.length, 'isMp4success', this.isMp4success)

      this.loading = true
      for (let i = 0; i < this.fileList.length; i++) {
        console.log('this.fileList.length22222222', this.fileList.length)
        let file = this.fileList[i].raw
        console.log("file", file, 'file.name', file.name)
        let filename = file.name;
        let markIndex = (filename).lastIndexOf('.');
        let suffix = filename.substring(markIndex)
        let name = filename.substring(0, markIndex); // 截取除 .png前的字段名
        console.log('markIndex,suffix', markIndex, suffix)
        let date = new Date().getTime();
        // 构建请求参数
        let param = new FormData()
        param.append("key", this.data.dir + name + '.' + date + suffix)
        param.append("policy", this.data.policy)
        param.append("OSSAccessKeyId", this.data.accessId)
        param.append("success_action_status", '200')
        // param.append("callback",  this.data.callback)     //回调（not)
        param.append("signature", this.data.signature)
        param.append("file", file, file.name)
        param.append('success_action_status', '200')
        let config = {
          headers: {
            'Access-Control-Allow-Origin': '*',
            'x-oss-callback-Authorization': getToken()
          }
        }
        axios.post(this.data.host, param, config).then(res => {
          if (res.status == 200) {
            // 修改
            // this.$refs.upload.submit();  // 图片上传进度
            console.log('this.data.host', this.data.host + '/' + name + '.' + date + suffix)
            let url = this.data.host + '/' + name + '.' + date + suffix;
            let type = file.type;
            console.log('进入上传file.type=====', file.type)
            // this.fileList=[]
            this.onDone(url);
            this.loading = false
            this.$message.success('上传成功');
            this.updateVisible(false);
            // this.registerMedias(url, type);
          } else {
            this.loading = false
            this.$message.error('上传失败');
          }

        }).catch(err => {
          console.log(err)
        })
      }
    },

    // registerMedias (url, type) {
    //   // registerMedia({
    //   registerAssetsMedia({
    //     mediaUrl: url,//上传阿里云生成的地址
    //     mediaType: type,//文件类型
    //     username: this.$store.state.user.info.username,
    //     folderId: this.parentId
    //   })
    //     .then((data) => {
    //       this.isNum++
    //       console.log("this.isNum", this.isNum, 'this.fileList.length', this.fileList.length)
    //       // setTimeout(()=>{
    //       // (修改隐藏)
    //       console.log("媒资111122=======data", data)
    //       addTrailer({
    //         mediaId: data.data.mediaId,//媒资id
    //         duration: data.data.duration,//媒资时长
    //         fileUrl: data.data.mediaUrl, // 媒资地址
    //         types: this.types, //1:片头 2：片尾
    //         merchantId: this.$store.state.user.info.merchantId, // 商家id

    //       })
    //         .then((data) => {
    //           if (this.fileList.length == this.isNum) {
    //             this.$message.success('上传成功');
    //             this.loading = false
    //             //关闭弹窗
    //             this.updateVisible(false);
    //             // 清空已上传的文件列表（该方法不支持在 before-upload 中调用）
    //             this.$refs['upload'].clearFiles()
    //             this.onDone();
    //           }

    //         })
    //         .catch((e) => {
    //           this.$message.error(e.message);
    //           this.loading = false
    //         });
    //       // },500)
    //     })
    //     .catch((e) => {
    //       this.loading = false
    //       this.$message.error(e.message);
    //     });
    // },
    /* 更新 visible */
    updateVisible (value) {
      this.loading = false
      // 除了上传时，为了避免重复调用push_fileList,所以在上传时标识isFile为true，return_push
      this.isFile = false
      this.fileList = []
      this.$emit('update:visible', value);
    },
    //文件超出个数限制时的钩子
    handleExceed (files, fileList) {
      console.log("进入文件超出个数限制时的钩子======", files.length, 'this.residueLength', this.residueLength)
      this.$message.warning(`当前限制选择 ${this.residueLength} 个文件，本次选择了 ${files.length} 个文件`);
    },

    //
    async beforeAvatarUpload (file) {
      /* const isJPG = file.type === 'image/jpeg';
       const isLt2M = file.size / 1024 / 1024 < 2;
	
       if (!isJPG) {
       this.$message.error('上传头像图片只能是 JPG 格式!');
       }
       if (!isLt2M) {
       this.$message.error('上传头像图片大小不能超过 2MB!');
       }
       return isJPG && isLt2M;*/
      const isMp4success = await this.getMp4Time(file); // 视频时长
      this.isMp4success = isMp4success
      await new Promise(async (resolve, reject) => {
        console.log("isMp4success========", isMp4success)
        if (isMp4success * 1 <= 3) {
          // this.$message.error('上传视频长度不能低于3秒');
        }
      })


      /* const isMp4success = this.getMp4Time(file);
       console.log("isMp4success========",isMp4success,'222',isMp4success.PromiseResult)
	
       if (isMp4success * 1 > 5) {
       _this.$message.error('上传视频长度不能超过 5 秒');
       }*/
      // return isMp4success * 1 > 5 == false ? Promise.resolve() : Promise.reject();
      return reject(false);;
    },

    //上传之前的钩子
    async beforeAvatarUpload2 (file) {
      let _this = this;
      // 判断视频格式，根据需求随便加
      if (['video/mp4', 'video/ogg', 'video/wmv'].indexOf(file.type) == -1) {
        this.$message.error('请上传正确的视频格式');
        return Promise.reject(false);//之前我直接返回的false、true没有效果，改成返回Promise了
      } else {
        return await new Promise(async (resolve, reject) => {
          let isMp4success = await _this.getMp4Time(file); // 视频时长
          console.log("isMp4success========", isMp4success)
          if (isMp4success * 1 < 5) {
            resolve(true);
          } else {
            _this.$message.error('上传视频长度不能超过 5 秒');
            reject(false);
          }
        })
      }
    },
    // 获取视频时长
    getMp4Time (file) {
      return new Promise(async (resolve, reject) => {
        let url = URL.createObjectURL(file);
        let audioElement = new Audio(url);
        let durtaion = 0;
        // 下面需要注意的是在监听loadedmetadata绑定的事件中对duration直接进行赋值是无效的，需要在fun回调函数中进行赋值
        audioElement.addEventListener("loadedmetadata", function () {
          //音频/视频的元数据已加载时，会发生 loadedmetadata 事件
          durtaion = audioElement.duration; //时长以秒作为单位
          fun(parseFloat(durtaion).toFixed(1))
        });
        let fun = (s) => {
          durtaion = s;
          resolve(durtaion)
        };
      })
    },



    /* 上传 */
    onUpload (file) {
      console.log('this.isMp4success222222222', this.isMp4success)

      // 修改
      if (this.isFile == true) {
        return
      }
      this.fileList.push(file)
      console.log('this.fileList', this.fileList)
    },

    /* 完成刷新列表数据 */
    onDone (url) {
      this.$emit('done', url);
    },
  }
}
	</script>
	
	<style scoped>
/deep/ .el-upload-dragger {
  width: 420px !important;
}

/* 上传组件 —— 下load（加载中）图标样式 */
/deep/ .el-upload-dragger .el-icon-loading {
  font-size: 67px;
  color: var(--color-text-placeholder);
  margin: 40px 0 16px;
  line-height: 50px;
}
</style>
	